<template>
  <div class="user-collections">
    <el-card>
      <div slot="header" class="clearfix">
        <span>我的收藏</span>
      </div>
      
      <div class="empty-block" v-if="collectionsList.length === 0">
        <el-empty description="暂无收藏，去首页发现更多精彩作品吧！">
          <el-button type="primary" @click="$router.push('/')">去发现</el-button>
        </el-empty>
      </div>
      
      <div v-else class="collections-list">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in collectionsList" :key="item.id">
            <el-card shadow="hover" class="collection-card" @click.native="viewDetail(item.photoId)">
              <div class="image-container">
                <el-image 
                  :src="item.imgUrl" 
                  fit="cover">
                  <div slot="error" class="image-error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
              <div class="info">
                <h3 class="title">{{ item.title }}</h3>
                <div class="author">
                  <img :src="item.avatar || defaultAvatar" class="avatar" />
                  <span>{{ item.username }}</span>
                </div>
                <div class="actions">
                  <el-button 
                    type="text" 
                    icon="el-icon-star-off"
                    @click.stop="cancelCollection(item)" 
                    class="cancel-btn">
                    取消收藏
                  </el-button>
                  <span class="time">{{ formatDate(item.createTime) }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <div class="pagination" v-if="total > 0">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserCollections',
  data() {
    return {
      collectionsList: [],
      currentPage: 1,
      pageSize: 12,
      total: 0,
      loading: false,
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    this.fetchUserCollections()
  },
  methods: {
    async fetchUserCollections() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          userId: this.userId
        }
        const res = await this.$http.get('/collections/user', { params })
        if (res.data.code === 1) {
          this.collectionsList = res.data.data.records.map(item => {
            if (item.imgUrl && item.imgUrl.startsWith('/upload/')) {
              item.imgUrl = `${window.location.origin}/api${item.imgUrl}`;
              console.log('收藏图片URL:', item.imgUrl);
            }
            return item;
          });
          this.total = res.data.data.total
        } else {
          this.$message.error('获取收藏列表失败')
        }
      } catch (error) {
        console.error('获取收藏列表失败', error)
        this.$message.error('获取收藏列表失败')
      } finally {
        this.loading = false
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchUserCollections()
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    viewDetail(id) {
      this.$router.push(`/detail/${id}`)
    },
    async cancelCollection(item) {
      try {
        await this.$confirm('确定取消收藏该作品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await this.$http.delete(`/collections/${item.id}`)
        if (res.data.code === 1) {
          this.$message.success('取消收藏成功')
          this.fetchUserCollections()
        } else {
          this.$message.error(res.data.msg || '取消收藏失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消收藏失败', error)
          this.$message.error('取消收藏失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.empty-block {
  margin: 40px 0;
}

.collections-list {
  margin-top: 20px;
}

.collection-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.collection-card:hover {
  transform: translateY(-5px);
}

.image-container {
  height: 200px;
  overflow: hidden;
}

.el-image {
  width: 100%;
  height: 100%;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.info {
  padding: 10px 0;
}

.title {
  margin: 0 0 10px;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.author {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 6px;
}

.actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.time {
  color: #909399;
}

.cancel-btn {
  padding: 0;
}

.pagination {
  margin-top: 30px;
  text-align: right;
}
</style> 